(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:ShopCtr
     * @description
     * # ShopCtr
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('ShopCtr', ShopCtr);

    ShopCtr.$inject = ['$scope', 'dataService', '$location', '$filter', 'helper', 'base64', 'topService', 'ERP_CONFIG', '$timeout'];

    function ShopCtr($scope, dataService, $location, $filter, helper, base64, topService, ERP_CONFIG, $timeout) {

        $scope.auth2url = function() {
            console.log("----", location)
            var url = location.origin + location.pathname + "#/shop/auth2";
            return $filter("url_encode")(url);
        }

        //同步淘宝商品
        $scope.syncItem = function($event) {
            dataService.thirdTopItemAdd($scope.shop.shop_id).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("error:" + r.Msg);
                } else {
                    if ($event) {
                        helper.myTip("success", $event.currentTarget, null, null, null, "bottom");
                        $timeout(function() {
                            $scope.itemData();
                        }, 3000);
                    } else {
                        helper.myAlert("success", "#/shop/item?shop_id=" + $scope.shop.shop_id);
                    }
                }
            })
        }


        //淘宝商品列表
        $scope.itemAction = function() {
            $scope.shop_id = $location.search().shop_id;
            if (!$scope.shop_id) {
                return helper.myAlert("error shop_id", "#/shop/list");
            }

            dataService.shopOne($scope.shop_id).then(function(s) {
                $scope.shop = s;
            });

            //请求商品
            $scope.itemsTotal = 0;
            $scope.pageSize = 10;
            $scope.itemData();
        }


        $scope.itemData = function(pageNo) {
            var query = {
                page_no: pageNo,
                page_size: $scope.pageSize
            };

            var q = {};
            if ($scope.shop_id) {
                q = { "shop_id": $scope.shop_id };
            }

            if ($scope.src_item_id) {
                q["src_item_id"] = $scope.src_item_id;
            }

            query.query = q;

            return dataService.thirdTopItemGet(query).then(function(data) {
                $scope.items = data.src_items;
                $scope.itemsTotal = data.total_count;
            });

        }


        //auth2授权创建店铺
        $scope.auth2Action = function() {
            var tk = $location.search().k;
            if (tk) {
                var token = JSON.parse(base64.decode(tk));
                console.log("token", token);
                if (token.taobao_user_id) {
                    topService.taobaoShopGet(token.taobao_user_nick, token.access_token).then(function(tbshop) {
                        $scope.shop = {
                            type_id: 1,
                            name: tbshop.title,
                            url: "http://shop" + tbshop.sid + ".taobao.com",
                            outer_id: tbshop.sid,
                            seller_id: token.taobao_user_id,
                            seller_nick: token.taobao_user_nick,
                            session: token.access_token,
                            app_key: token.appkey,
                            token_json: angular.toJson({
                                token: token,
                                shop: tbshop,
                            }),
                        }
                    })
                } else {
                    helper.myAlert("error:" + tk, "#/shop/list");
                }
            } else {
                $scope.shop_id = $location.search().shop_id;
                if ($scope.shop_id) {
                    dataService.shopOne($scope.shop_id).then(function(shop) {
                        $scope.shop = shop;
                    });
                } else {
                    helper.myAlert("error: invalid shop_id");
                }
            }
        }

        //列表
        $scope.listAction = function() {
            $scope.addrsTotal = 0;
            $scope.pageSize = 10;
            $scope.getShopList();
        }

        //获取shop列表
        $scope.getShopList = function(pageNo) {
            var query = { page_no: pageNo, page_size: $scope.pageSize };
            var q = [];
            dataService.shopGet(query).then(function(list) {
                if (list && list.shop) {
                    $scope.shopList = list.shop;
                    $scope.shopTotal = list.total_count;
                }
            });
        }

        //创建
        $scope.addAction = function() {
            $scope.shop_id = $location.search().shop_id;
            if ($scope.shop_id) {
                dataService.shopOne($scope.shop_id).then(function(shop) {
                    $scope.shop = shop;
                });
            } else {
                $scope.shop = {};
            }
        }

        $scope.shopAdd = function() {
            if ($scope.shop_id) {
                dataService.shopUp($scope.shop).then(function(result) {
                    if (result.Msg) {
                        helper.myAlert("error" + result.Msg);
                    } else {
                        helper.myAlert("success", "#/shop/list");
                    }
                });
            } else {
                dataService.shopAdd($scope.shop).then(function(result) {
                    if (result.Msg) {
                        helper.myAlert("error" + result.Msg);
                    } else {
                        helper.myAlert("success", "#/shop/list");
                    }
                });
            }
        }

        //删除店铺
        $scope.delShop = function(shop_id) {
            var query = { "shop_id": shop_id };
            dataService.shopDel(query).then(function(result) {
                if (result.Msg) {
                    helper.myAlert("error" + result.Msg);
                } else {
                    $scope.getShopList(1);
                }
            });
        }


        //添加淘宝同步的商品
        $scope.addTbItem = function(item) {

            if (!item.outer_id) {
                helper.myAlert("error" + "outer_id null");
                return;
            }
            var skus = [];
            $scope.addItemdata = {
                company_id: $scope.shop_id, //公司id
                outer_id: item.outer_id, //外部商品编码
                title: item.src_json.title,
                cid: 1,
                stocks_warning: 1,
                desc: item.src_json.desc,
                express_fee: item.src_json.express_fee,
                pic_url: item.src_json.pic_url,
                unit_id: item.unit_id,
                // shape_id: '',
                volume_unit_id: item.volume_unit_id,
                weight_unit_id: item.weight_unit_id,
                remark: "",
            };
            if (item.src_json.skus.sku) {
                _.map(item.src_json.skus.sku, function(da, key) {
                    if (!da.outer_id) {
                        helper.myAlert("error: outer_id is null");
                        return;
                    }
                    skus[key] = {
                        outer_id: da.outer_id,
                        properties_name: da.properties_name,
                        input_price: da.price,
                        output_price: da.price,
                        status: da.status == "normal" ? 1 : 2, //1代表正常，2代表删除
                        remark: "", //备注
                        weight: item.src_json.item_weight ? item.src_json.item_weight : 1, //重量
                        volume: item.src_json.item_size ? item.src_json.item_size : 1, //体积
                        barcode: da.barcode, //条码
                    };
                });
            } else {
                skus[0] = {
                    outer_id: "",
                    properties_name: item.src_json.title,
                    input_price: item.src_json.price,
                    output_price: item.src_json.price,
                    status: 1, //1代表正常，2代表删除
                    remark: "", //备注
                    volume: 1,
                    weight: 1,
                    barcode: item.src_json.outer_id, //条码
                };
            }
            $scope.addItemdata.skus = skus;
            if ($scope.addItemdata.outer_id) {
                return dataService.itemadd($scope.addItemdata).then(function(r) {
                    if (r.Msg) {
                        helper.myAlert("error:" + r.Msg);
                    }
                })
            }
        }

        //编辑淘宝商品增加ouid
        $scope.itemeditAction = function() {
            $scope.shop_id = $location.search().shop_id;
            var src_item_id = $location.search().src_item_id;
            var istype = $location.search().istype;
            var query = {};
            if ($scope.shop_id) {
                query = { "shop_id": $scope.shop_id };
            }

            if (src_item_id) {
                query["src_item_id"] = src_item_id;
            } else {
                helper.myAlert("error src_item_id in null ");
                return;
            }
            $scope.shopitem = '';
            dataService.thirdTopItemGet({ query: query }).then(function(data) {
                if (data) {
                    $scope.itemData = data.src_items[0];
                    if ($scope.itemData.src_json.skus.sku) {
                        $scope.shopitem = '1';
                    }

                    $scope.item = clone($scope.itemData);
                    return $scope.item;
                }
            }).then(function(item) {
                if (item && istype) {
                    query = { "outer_id": item.outer_id };
                    dataService.itemGet({ query: query }).then(function(list) {
                        if (list) {
                            var items = list.items[0];
                            if (items) {
                                $scope.erpitem = items;
                            }
                        }
                    });
                }
            });
        }

        //单选框选择类型
        $scope.isChecked = function(type) {
            if (type == 1) {
                $scope.select_item = {};
                $scope.itemone = 1;
                $scope.itemtwo = '';
            }
            if (type == 2) {
                $scope.itemtwo = 1;
                $scope.itemone = '';
                $scope.select_item = {};

                $scope.item = clone($scope.itemData);
                // console.log("$scope.item", $scope.item);
            }
        }

        //选中erp中商品
        $scope.getitem = function(items, oid) {
            $scope.select_item = $scope.select_item || {};
            if (items) {

                if (oid) {
                    $scope.select_item[oid] = items;
                    _.map($scope.order.src_json.trade_fullinfo_get_response.trade.orders.order, function(da, ke) {
                        if (da.oid == oid) {
                            da.outer_iid = items.outer_id;
                            da.sku_id = items.sku_data.sku_id;
                            da.item_id = items.item_id;
                            da.outer_sku_id = items.sku_data.outer_id ? items.sku_data.outer_id : 0;
                        }
                    });
                } else {
                    $scope.select_item = items;;
                }
                console.log("ccccc", $scope.select_item, oid);
            }
        }

        //更新淘宝商品的outerid
        $scope.upItemOuterid = function() {
            if ($scope.item) {
                if ($scope.itemone) {
                    $scope.item.outer_id = $scope.select_item.outer_id;
                }
                if ($scope.shop_id) {
                    dataService.shopOne($scope.shop_id).then(function(shop) {
                        $scope.shop = shop;
                        return $scope.shop;
                    }).then(function(shop) {
                        var session = $scope.shop.session;
                        if ($scope.item.src_json.skus.sku) {
                            var len = $scope.item.src_json.skus.sku.length;
                            _.map($scope.item.src_json.skus.sku, function(dae, key) {
                                topService.taobaoItemSkuUpdate($scope.item.src_json.num_iid, dae.properties, dae.outer_id, session).then(function(re) {
                                    if (re.error_response) {
                                        helper.myAlert("error" + re.error_response.msg);
                                    } else {
                                        if (len == key + 1) {
                                            $scope.upitemOuteId($scope.item.src_json.num_iid, $scope.item.outer_id, session).then(function(re) {
                                                if (re.item_update_response) {
                                                    if ($scope.itemtwo) {
                                                        $scope.addTbItem($scope.item);
                                                    }
                                                    $scope.syncItem();
                                                } else {
                                                    helper.myAlert("error" + re.error_response.msg);
                                                }
                                            });
                                        }
                                    }
                                });
                            });
                        } else {
                            $scope.upitemOuteId($scope.item.src_json.num_iid, $scope.item.outer_id, session).then(function(re) {
                                if (re.item_update_response) {
                                    if ($scope.itemtwo) {
                                        $scope.addTbItem($scope.item);
                                    }
                                    $scope.syncItem();
                                } else {
                                    helper.myAlert("error" + re.error_response.msg);
                                }
                            });
                        }
                    });
                }
            }
        }

        //修改商品outur_id 
        $scope.upitemOuteId = function(num_iid, outer_id, session) {
            return topService.taobaoItemUpdate(num_iid, outer_id, session).then(function(re) {
                return re;
            });
        }

        //订单
        $scope.orderAction = function() {
            $scope.shop_id = $location.search().shop_id;
            if (!$scope.shop_id) {
                return helper.myAlert("error shop_id", "#/shop/list");
            }
            $scope.pageSize = 10;
            dataService.shopOne($scope.shop_id).then(function(s) {
                $scope.shop = s;
                $scope.orderData(1);
            });
        }

        // 同步订单
        $scope.syncOrder = function($event) {
            var data = { shop_id: $scope.shop_id, seller_nick: $scope.shop.seller_nick, switch: 2 };
            dataService.thirdToporderRdssync(data).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("error:" + r.Msg);
                } else {
                    helper.myTip("success", $event.currentTarget, null, null, null, "bottom");
                    $timeout(function() {
                        $scope.orderData();
                    }, 3000);
                }
            })
        }

       

      
       
    }
})();
